"""
管理员账号初始化脚本
"""

import os
from dotenv import load_dotenv
from datetime import datetime, UTC
from sqlalchemy.orm import Session

from models.user import User, UserRole, UserStatus
from dao.postgresql_connect import SessionLocal
from utils import get_password_hash

def init_admin():
    """初始化管理员账号"""
    load_dotenv()
    
    # 检查必要的环境变量
    required_vars = ['ADMIN_USERNAME', 'ADMIN_EMAIL', 'ADMIN_PASSWORD']
    missing_vars = [var for var in required_vars if not os.getenv(var)]
    if missing_vars:
        raise ValueError(f"缺少必要的环境变量: {', '.join(missing_vars)}")
    
    db = SessionLocal()
    try:
        # 检查是否已存在管理员账号
        admin = db.query(User).filter(User.role == UserRole.ADMIN).first()
        if not admin:
            # 创建管理员账号
            admin = User(
                username=os.getenv('ADMIN_USERNAME'),
                email=os.getenv('ADMIN_EMAIL'),
                password=get_password_hash(os.getenv('ADMIN_PASSWORD')),
                role=UserRole.ADMIN,
                status=UserStatus.ACTIVE,
                created_at=datetime.now(UTC),
                updated_at=datetime.now(UTC)
            )
            db.add(admin)
            db.commit()
            print(f"管理员账号创建成功: {admin.username}")
        else:
            print("管理员账号已存在")
    except Exception as e:
        print(f"创建管理员账号失败: {str(e)}")
        raise
    finally:
        db.close()

if __name__ == '__main__':
    init_admin() 